//
//  ICSingleTextField.swift
//  Dawn
//
//  Created by cuicheng on 2021/9/27.
//

import UIKit

enum ICSingleTextFieldStyle {
    case line(height: CGFloat, color: UIColor)
    case border(width: CGFloat, color: UIColor, corner: CGFloat)
}

class ICSingleTextField: UIView {
    
    struct ICSingleTextFieldConfig {
        var count = 4
        var font: UIFont = .font(15)
        var textColor: UIColor = .black
        var itemWidth: CGFloat = 50.adapter
        var style = ICSingleTextFieldStyle.line(height: 0.8.adapter, color: .black)
    }
    
    var config = ICSingleTextFieldConfig()
    var textChangeClosure: ((String?, Bool)->())?
    private func _initUI() {
        guard viewWithTag(singleTag) == nil else { return }
        let spacing = (bounds.width - (config.itemWidth * CGFloat(config.count))) / CGFloat(config.count - 1)
        for i in 0..<config.count {
            let tf = ICBackTextField()
            tf.tag = singleTag + i
            tf.font = config.font
            tf.textColor = config.textColor
            tf.textAlignment = .center
            tf.keyboardType = .numberPad
            tf.delegate = self
            tf.backDelegate = self
            tf.frame = CGRect(x: CGFloat(i) * (config.itemWidth + spacing), y: 0, width: config.itemWidth, height: bounds.height)
            switch config.style {
            case .line(let height, let color):
                tf.da.line(height: height, color: color)
            case .border(let width,let color,let corner):
                tf.da.corner(radius: corner, borderWidth: width, borderColor: color)
            }
            addSubview(tf)
        }
    }

    override func layoutSubviews() {
        super.layoutSubviews()
        _initUI()
    }
    
    var isComplete: Bool {
        var _isComplete = true
        for i in 0..<config.count {
            let tf = viewWithTag(singleTag + i) as? UITextField
            if (tf?.text?.count ?? 0 ) == 0 {
                _isComplete = false
            }
        }
        return _isComplete
    }
    
    var text: String {
        var _str = ""
        for i in 0..<config.count {
            let str = (viewWithTag(singleTag + i) as? UITextField)?.text ?? ""
            _str += str
        }
        return _str
    }
    
    private let singleTag = 777
}

protocol ICBackTextFieldDelegate {
    func deleteBackward(_ tf: UITextField)
}

private class ICBackTextField: UITextField {
    var backDelegate: ICBackTextFieldDelegate?
    override func deleteBackward() {
        backDelegate?.deleteBackward(self)
    }
    override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
        if action == #selector(canPaste(_:)) {
            return false
        }
        if action == #selector(select(_:)) {
            return false
        }
        if action == #selector(selectAll(_:)) {
            return false
        }
        return super.canPerformAction(action, withSender: sender)
    }
}

extension ICSingleTextField: UITextFieldDelegate {
    
    func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
        let lastTf = viewWithTag(textField.tag + 1) as? UITextField
        if (lastTf?.text?.count ?? 0) > 0 {
            return false
        }
        return true
    }
    
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        
        let textCount = textField.text?.count ?? 0
        if string == "" {
            if textField.tag == singleTag {
                textChangeClosure?(text, false)
                return true
            }
            
            textField.text = nil
            let lastTf = viewWithTag(textField.tag - 1) as? UITextField
            if textCount == 0 {
                lastTf?.text = nil
            }
            textChangeClosure?(text, false)
            return false
        }
        
        if textCount == 0 {
            textField.text = string
            if textField.tag - singleTag == config.count - 1 {
                ///最后一个输入框
                
                textChangeClosure?(text, true)
            }else {
                let lastTf = viewWithTag(textField.tag + 1) as? UITextField
                lastTf?.becomeFirstResponder()
                textChangeClosure?(text, false)
            }
            return false
        }
        
        if textCount == 1 {
            textField.resignFirstResponder()
            let nextTf = viewWithTag(textField.tag + 1) as? UITextField
            nextTf?.becomeFirstResponder()
            nextTf?.text = string
            textChangeClosure?(text, false)
            return false
        }
        
        return false
    }
    
}

extension ICSingleTextField: ICBackTextFieldDelegate {
    func deleteBackward(_ tf: UITextField) {
        let textCount = tf.text?.count ?? 0
        tf.text = nil
        let lastTf = viewWithTag(tf.tag - 1) as? UITextField
        if textCount == 0 {
            lastTf?.text = nil
            lastTf?.becomeFirstResponder()
        }
    }
}
